//Package middleware ...
/*
 * @Descripttion:
 * @Author: congz
 * @Date: 2020-06-10 10:58:11
 * @LastEditors: congz
 * @LastEditTime: 2020-08-05 15:12:36
 */
package middleware

import (
	"regexp"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

// Cors 跨域配置
func Cors() gin.HandlerFunc {
	config := cors.DefaultConfig()
	config.AllowMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
	config.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Cookie", "Authorization"}
	// config.AllowOrigins = []string{"http://localhost:8080", "http://localhost:8081", "http://j9grvkwx.shenzhuo.vip:12131","http://localhost:3000","http://localhost:3001","http://localhost:3002","http://192.168.2.120:8080","http://192.168.2.120:12345","http://192.168.2.120:3001","http://192.168.2.120:3002"}
	
	// 测试环境下模糊匹配本地开头的请求
	config.AllowOriginFunc = func(origin string) bool {
		if regexp.MustCompile(`^http://127\.0\.0\.1:\d+$`).MatchString(origin) {
			return true
		}
		if regexp.MustCompile(`^http://localhost:\d+$`).MatchString(origin) {
			return true
		}
		if regexp.MustCompile(`^http://j9grvkwx\.shenzhuo\.vip:\d+$`).MatchString(origin) {
			return true
		}
		return true
	}

	config.AllowCredentials = true
	return cors.New(config)
}
